package com.lulalei.dbviewer.commons.bean;

import com.lulalei.dbviewer.commons.cache.CacheManager;
import com.lulalei.dbviewer.commons.cache.CacheMap;
import com.lulalei.dbviewer.commons.exception.CustomizeException;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * <p>
 * jdbc对象
 * </p>
 *
 * @author lulalei
 * @create 2021-05-14 20:09
 */
@Slf4j
public class JDBCConnectBean {
    /**
     * 数据连接的相关信息
     */
    private final DBInfo dbInfo;

    /**
     * 数据库连接对象
     */
    private Connection connection;

    public JDBCConnectBean(DBInfo dbInfo,boolean test) throws CustomizeException {
        this.dbInfo = dbInfo;
        try {
            Class.forName(dbInfo.getDriverClassName());
            connection = DriverManager.getConnection(dbInfo.getUrl(), dbInfo.getUsername(), dbInfo.getPassword());
        } catch (Exception e) {
            //链接失败
            String message = e.getMessage();
            if (message.contains("using password: YES")) {
                throw new CustomizeException("用户名或密码错误");
            }
            if (message.contains("Driver")) {
                throw new CustomizeException("请检查数据库驱动是否配置正确");
            }
            throw new CustomizeException("服务链接超时，请检查url是否正确或数据库服务是否开启");
        }

        if (test) {
            connection = null;
        } else {
            //连接成功后自动保存到缓存中
            putCacheMap();
        }

    }

    /**
     * 获取connection对象
     *
     * @return connection对象
     */
    public Connection getConnection() {
        return connection;
    }

    /**
     * 关闭数据库链接
     */
    public void close() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 将数据库连接对象存入缓存
     */
    private void putCacheMap() {
        CacheMap jdbc = CacheManager.getNotNullCacheMap("jdbc");
        jdbc.put(dbInfo.getName(), this);
    }

    public DBInfo getDbInfo() {
        return dbInfo;
    }
}
